package com.yyk.yykywd.mvvm.ui

import android.os.Handler
import android.os.Message
import android.view.KeyEvent
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.google.gson.Gson
import com.yyk.yykywd.*
import com.yyk.yykywd.bean.BaseBean
import com.yyk.yykywd.mvvm.adapter.AddMaterialAdapter
import com.yyk.yykywd.mvvm.base.BaseTakePhotoActivity
import com.yyk.yykywd.mvvm.entity.UploadBean
import com.yyk.yykywd.mvvm.event.FinishWorkDetail
import com.yyk.yykywd.mvvm.view_model.AddPictureViewModel
import com.yyk.yykywd.util.DensityUtils
import com.yyk.yykywd.util.ToastUtil
import com.yyk.yykywd.widght.SpaceItemDecoration
import kotlinx.android.synthetic.main.activity_add_material.*
import kotlinx.android.synthetic.main.activity_completion_contract.*
import kotlinx.android.synthetic.main.rl_bottom.*
import org.devio.takephoto.model.TResult
import org.greenrobot.eventbus.EventBus

class CompletionContractActivity : BaseTakePhotoActivity() {
    private lateinit var viewModel: AddPictureViewModel
    private lateinit var adapter: AddMaterialAdapter

    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val result = msg.obj as String
            val gson = Gson()
            val info: UploadBean = gson.fromJson(result, UploadBean::class.java)
            if (info.code != 1) {
                ToastUtil.showShort(mActivity, info.msg)
                return
            }

            viewModel.contract_imgs.add(info.data)
            adapter.notifyDataSetChanged()
        }
    }

    override fun initData() {
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_completion_contract
    }

    override fun initView() {
        viewModel = getViewModel(this, AddPictureViewModel::class.java)
        setBackArrow {
            backAndDelImg()
        }
        setTitle("补全合同")
        with(viewModel) {
            id = intent.getStringExtra(ID)
            pact_id = intent.getStringExtra(PACT_ID)
            back_money_num = intent.getIntExtra(BACK_MONEY_NUM, 0)
            rxhk_money = intent.getIntExtra(RXHK_MONEY, 0)
        }


        rv_contract_img.layoutManager = GridLayoutManager(mActivity, 3)
        rv_contract_img.addItemDecoration(SpaceItemDecoration(DensityUtils.dp2px(mActivity, 10f)))
        adapter = AddMaterialAdapter(mActivity, viewModel.contract_imgs)
        adapter.maxImages = AddMaterialActivity.MAX_IMAGES
        rv_contract_img.adapter = adapter
    }

    override fun takeSuccess(result: TResult) {
        viewModel.uploadContractImg(CONTRACT, result.image.compressPath)
    }

    override fun setListener() {
        super.setListener()

        tv_execute.setOnClickListener {
            if (required()) {
                return@setOnClickListener
            }
            if (viewModel.back_money_num == 1 && viewModel.rxhk_money == 0) {
                show(mActivity, "是否确认补全合同信息",
                        "保存后本次业务回款完成，您可在\"全款合同列表\"中查看此项业务",
                        "确认",
                        "取消") {
                    viewModel.completionContract(getTextString(et_contract_num))
                }
            } else {
                show(mActivity, "",
                        "是否确认补全合同信息",
                        "确认",
                        "取消") {
                    viewModel.completionContract(getTextString(et_contract_num))
                }
            }

        }

        viewModel.responseMessage.observe(this, Observer<String> { t ->
            val msg = Message.obtain()
            msg.what = 1
            msg.obj = t
            handler.sendMessage(msg)
        })

        viewModel.delSuccess.observe(this, Observer<BaseBean> {
            if (it.code != 200) {
                ToastUtil.showShort(it.msg)
                return@Observer
            }
            if (viewModel.delSingleOrMulti == MULTI) {
                finish()
                return@Observer
            }
            viewModel.contract_imgs.removeAt(viewModel.del_position)
            adapter.notifyDataSetChanged()
        })

        setAdapterChildClickListener(mActivity, adapter,
                getTakePhoto(),
                1, object : UploadClickListener {
            override fun clickIv() {

            }

            override fun clickRemove(position: Int) {
                viewModel.del_position = position
                viewModel.delSingleOrMulti = SINGLE
                viewModel.removeImg(viewModel.contract_imgs[position])
            }

        })

        viewModel.completionContractSuccess.observe(this, Observer {
            ToastUtil.showShort(it.msg)
            if (it.code == 200) {
                if (viewModel.back_money_num == 1 && viewModel.rxhk_money == 0) {
                    EventBus.getDefault().post(FinishWorkDetail())
                }
                finish()
            }
        })
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            backAndDelImg()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun backAndDelImg() {
        with(viewModel) {
            val list = contract_imgs
            if (list.isNotEmpty()) {
                delSingleOrMulti = MULTI
                removeImg(listToString(list))
            } else {
                finish()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }

    private fun required(): Boolean {
        val s = getTextString(et_contract_num)
        if (s.isEmpty()) {
            ToastUtil.showShort("请填写合同编号")
            return true
        }
        if (viewModel.contract_imgs.isEmpty()) {
            ToastUtil.showShort("请上传合同图片")
            return true
        }
        return false
    }
}
